var express = require("express");
var router = express.Router();
let myQuery = require("../tools/db")
let { apiUrl, md5suo, jwtsuo } = require("../tools/config")
let md5 = require('md5')
let { jwtSign } = require('../tools/token')
let { v4: uuid } = require('uuid')

//登录
router.post('/login', async (req, res, next) => {
    let { username, password } = req.body

    // if (!username || !password) {
    //     next({ code: 400, msg: '用户名或密码不能为空' })
    //     return
    // }

    //对密码进行MD5加密
    password = md5(password + md5suo)

    let sql = `SELECT * FROM e_member WHERE username='${username}' AND password='${password}';`

    let [err, result] = await myQuery(sql)
    if (err) {
        next({ code: 500, msg: err })
        return
    }
    if (result.length > 0) {
        //登录成功 生成 token 返回给前端
        let data = {
            mid: result[0].mid,
            username: result[0].username
        }
        let token = jwtSign(data, jwtsuo, 7 * 24 * 3600)
        res.send({ code: 200, msg: 'ok', token })
    } else {
        next({ code: 400, msg: '用户名或密码错误' })
        return
    }
})


//注册
router.post('/register', async (req, res, next) => {
    let { username, password, pass2 } = req.body
    // if (!username || !password) {
    //     next({ code: 400, msg: '用户名或密码不能为空' })
    //     return
    // }
    // if (password != pass2) {
    //     next({ code: 400, msg: '密码两次输入不一致' })
    //     return
    // }
    //判断是否已注册
    let sql = `SELECT * FROM e_member WHERE username='${username}';`
    let [err, result] = await myQuery(sql)
    if (err) {
        next({ code: 500, msg: err })
        return
    }
    if (result.length > 0) {
        next({ code: 400, msg: '用户名已注册' })
        return
    }
    //创建 mid 密码加密 获取时间戳
    let mid = uuid()
    password = md5(password + md5suo)
    let time = Date.now()

    //进行注册
    let sql1 = `INSERT INTO e_member (mid,username,password,createdate) VALUES ('${mid}', '${username}','${password}',${time});`
    let [err1, result1] = await myQuery(sql1)
    if (err1) {
        next({ code: 500, msg: err1 })
        return
    }
    if(result1.insertId>0){
        res.send({code:200,msg:'注册成功'})
    }else{
        next({code:500,msg:'注册失败，请稍后再试'})
        return
    }
})

module.exports = router